package com.only4play.mybatis.support.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.only4play.auth.AuthenticatedUser;
import org.apache.ibatis.reflection.MetaObject;
import com.only4play.common.model.entity.RowStatus;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 拦截器
 *
 * @author liyuncong
 * @date 2023/11/10 11:43
 **/
@Component
public class AuditableAutofillInterceptor implements MetaObjectHandler {

    private AuthenticatedUser<?> currentUser() {
        return AuthenticatedUser.currentUser()
                .orElse(new AuthenticatedUser<>("admin", "admin", "0"));
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "rowStatus", Integer.class, RowStatus.OK);
        this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "updatedBy", Long.class, Long.parseLong(currentUser().getUserId()));
        this.strictUpdateFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "createdBy", Long.class, Long.parseLong(currentUser().getUserId()));

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "updatedBy", Long.class, Long.parseLong(currentUser().getUserId()));

    }
}
